package com.iwish.server.model;

import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;

import com.google.code.morphia.Datastore;
import com.iwish.server.storage.DAO.MongoDAO;
import com.iwish.server.storage.DAO.SQLCommand;
import com.iwish.server.storage.model.Obj;
import com.iwish.server.util.Base64Util;
import com.iwish.server.util.RequestCode;
import com.iwish.server.util.Separator;

public class LoginWithSinaAccountService extends ServiceTemplate{
	
	Logger logger = Logger.getLogger(LoginWithSinaAccountService.class);
	
	private String sina_account;
	
	public LoginWithSinaAccountService()
	{
		
	}
	
	public LoginWithSinaAccountService(String sina_account)
	{
		this.sina_account = sina_account;
	}
	
	public boolean login(IoSession session)
	{
			Object u = MongoDAO.execute(Obj.User.class, new SQLCommand() {
			
			@Override
			public Object sql(Class c, Datastore ds) {
				// TODO Auto-generated method stub
				return ds.find(c,"uname_",sina_account).get();
				
			}
			
			@Override
			public void print() {
				// TODO Auto-generated method stub
				logger.debug("LoginService - get user from DB");
				
			}
		});
		//logger.debug("get username = " + ((Obj.User)u).getUname());
		
		if(u == null || !(u instanceof Obj.User))
		{
			logger.debug(sina_account + " is new user");
			String result = Base64Util.encode(RequestCode.RESULT_LOGIN_SINA_ACCOUNT.getBytes())
					+ Separator.F_SEPARATOR
					+ Base64Util.encode(RequestCode.FAIL.getBytes())
					+ Separator.F_SEPARATOR;
			logger.info(result);
			session.write(result);
			return false;
		}
		String result = Base64Util.encode(RequestCode.RESULT_LOGIN_SINA_ACCOUNT.getBytes())
				+ Separator.F_SEPARATOR
				+ Base64Util.encode(RequestCode.SUCCESS.getBytes())
				+ Separator.F_SEPARATOR;
		logger.info(result);
		session.write(result);
		return true;
	}

}
